package com.letoken.platform.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.letoken.platform.admin.service.AdminAppService;
import com.letoken.platform.admin.service.AppUserWalletService;
import com.letoken.platform.admin.util.DateTimeUtil;
import com.letoken.platform.admin.util.LineChartUtil;
import com.letoken.platform.pub.constant.LetokenUserConstant;
import com.letoken.platform.pub.enums.*;
import com.letoken.platform.pub.exception.ApiServiceException;
import com.letoken.platform.pub.req.PageData;
import com.letoken.platform.pub.req.PageRes;
import com.letoken.platform.pub.util.BigDecimalUtil;
import com.letoken.platform.repo.admin.dao.*;
import com.letoken.platform.repo.admin.dto.RechargeAndSwapDto;
import com.letoken.platform.repo.admin.po.AdminUser;
import com.letoken.platform.repo.admin.po.AppEcoHistory;
import com.letoken.platform.repo.admin.po.Withdraw;
import com.letoken.platform.repo.admin.req.user.*;
import com.letoken.platform.repo.admin.res.user.*;
import com.letoken.platform.repo.app.dao.*;
import com.letoken.platform.repo.app.manager.AppUserAssetsHistoryManager;
import com.letoken.platform.repo.app.manager.AppUserLockedManager;
import com.letoken.platform.repo.app.manager.AppUserManager;
import com.letoken.platform.repo.app.manager.AppUserWalletManager;
import com.letoken.platform.repo.app.po.AppUser;
import com.letoken.platform.repo.app.po.AppUserAssetsHistory;
import com.letoken.platform.repo.app.po.AppUserTeam;
import com.letoken.platform.repo.app.po.AppUserWallet;
import com.letoken.platform.repo.app.redis.AppLoginTokenRedis;
import com.letoken.platform.repo.mall.dao.LevelUpHistoryMapper;
import com.letoken.platform.repo.utlis.PageDataUtil;
import com.letoken.platform.repo.utlis.WebUtils;
import com.letoken.platform.repo.wallet.redis.UserWalletRedisBloomFilter;
import com.letoken.platform.repo.wallet.req.WithdrawReq;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author letokenlabs
 * @date 2022/11/23$
 */
@Service
@Log4j2
public class AdminAppServiceImpl implements AdminAppService {

    @Autowired
    private AppUserMapper userMapper;

    @Autowired
    private AppUserManager userManager;

    @Autowired
    private AppUserTeamMapper appUserTeamMapper;

    @Autowired
    private AppUserTeamPathMapper teamPathMapper;

    @Autowired
    private AdminAppUserRechargeMapper appUserRechargeMapper;

    @Autowired
    private WithdrawMapper withdrawMapper;


    @Autowired
    private AppUserWalletManager appUserWalletManager;

    @Autowired
    private AppUserSwapRecordMapper appUserSwapRecordMapper;

    @Autowired
    private AppUserWalletMapper appUserWalletMapper;

    @Autowired
    private AppUserIssueMapper appUserIssueMapper;

    @Autowired
    private AppUserWalletService appUserWalletService;

    @Autowired
    private AppUserAssetsHistoryManager historyManager;

    @Autowired
    private AppUserLockedManager appUserLockedManager;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private AppUserAssetsHistoryMapper userAssetsHistoryMapper;

    @Resource
    private AppEcoHistoryMapper appEcoHistoryMapper;

    @Autowired
    LevelUpHistoryMapper levelUpHistoryMapper;


    /**
     * 查询app用户列表
     *
     * @param req
     * @return
     */
    @Override
    public PageData<QueryAppUserListRes> queryUserList(QueryAppUserListReq req) {
        Page<QueryAppUserListRes> page = new Page<>(req.getPageReq().getPage(), req.getPageReq().getSize());
        Page<QueryAppUserListRes> res = userMapper.queryUserList(page, req);

        HashSet<String> operatingCenters = appUserTeamMapper.operatingCenters();
        HashSet<String> partners = appUserTeamMapper.partners();

        for (QueryAppUserListRes record : res.getRecords()) {

            if(org.springframework.util.StringUtils.hasLength(record.getInvitePath()) && record.getInvitePath().contains(",")){
                String[] inviteIds = record.getInvitePath().split(",");

                boolean b1 = false;
                boolean b2 = false;

                for (String inviteId : inviteIds) {

                    if (StringUtils.isNotEmpty(inviteId)) {
                        if (StringUtils.isEmpty(record.getNearestCommunityLeader()) && operatingCenters.contains(inviteId) && !record.getUserId().equals(inviteId)) {
                            record.setNearestCommunityLeader(inviteId);
                            b1 = true;
                        }
                        if (null == record.getLeaderId() && partners.contains(inviteId)) {
                            record.setLeaderId(Integer.valueOf(inviteId));
                            b2 = true;
                        }

                        if(b1 && b2){
                            break;
                        }

                    }

                }
            }



        }
        return PageDataUtil.getPageData(res);
    }

    /**
     * 查询kol列表
     *
     * @param req
     * @return
     */
    @Override
    public PageData<QueryAppKolListRes> queryUserTeamList(QueryAppKolListReq req) {
        Page<QueryAppKolListRes> page = new Page<>(req.getPageReq().getPage(), req.getPageReq().getSize());
        Page<QueryAppKolListRes> teamPage = appUserTeamMapper.queryUserTeamList(page, req);
        return PageDataUtil.getPageData(teamPage);
    }

    /**
     * 查询充值记录
     *
     * @param req
     * @return
     */
    @Override
    public PageData<QueryAppDepositListRes> queryDepositList(QueryAppDepositListReq req) {
        Page<QueryAppDepositListRes> page = new Page<>(req.getPageReq().getPage(), req.getPageReq().getSize());
        Page<QueryAppDepositListRes> depositPage = appUserRechargeMapper.queryDepositList(page, req);
        return PageDataUtil.getPageData(depositPage);
    }

    /**
     * 查询提现记录
     *
     * @param req
     * @return
     */
    @Override
    public PageData<QueryAppWithdrawListRes> queryWithdrawList(QueryAppWithdrawListReq req) {
        if (req.getMaxNum() != null && req.getMinNum() != null) {
            if (req.getMaxNum().compareTo(req.getMinNum()) < 0) {
                throw new ApiServiceException("最大值不能小于最小值");
            }
        }
        Page<QueryAppWithdrawListRes> page = new Page<>(req.getPageReq().getPage(), req.getPageReq().getSize());
        Page<QueryAppWithdrawListRes> withdrawPage = withdrawMapper.queryWithdrawList(page, req);
        for (QueryAppWithdrawListRes record : withdrawPage.getRecords()) {
            if (record.getSource().equals("0")) {
                record.setAddress(LetokenUserConstant.USER_ID_PREFIX + record.getToId());
            }
        }
        return PageDataUtil.getPageData(withdrawPage);
    }

    /**
     * 查询提现审核
     *
     * @param req
     * @return
     */

    @Autowired
    AdminUserMapper adminUserMapper;

    @Override
    public PageData<QueryAppWithdrawAuditListRes> queryWithdrawAuditList(QueryAppWithdrawAuditListReq req) {
        if (req.getMaxNum() != null && req.getMinNum() != null) {
            if (req.getMaxNum().compareTo(req.getMinNum()) < 0) {
                throw new ApiServiceException("最大值不能小于最小值");
            }
        }
        Page<QueryAppWithdrawAuditListRes> page = new Page<>(req.getPageReq().getPage(), req.getPageReq().getSize());
        Page<QueryAppWithdrawAuditListRes> withdrawAuditPage = withdrawMapper.QueryAppWithdrawAuditListReq(page, req);
        if (!CollectionUtils.isEmpty(withdrawAuditPage.getRecords())) {
            withdrawAuditPage.getRecords().forEach(x -> {
                if (StringUtils.isNotBlank(x.getApprovedBy())) {
                    if (x.getApprovedBy().matches("[0-9]+")) {
                        AdminUser au = adminUserMapper.selectById(Integer.valueOf(x.getApprovedBy()));
                        if (!ObjectUtils.isEmpty(au))
                            x.setApprovedBy(au.getName());
                    }
                }
            });
        }
        return PageDataUtil.getPageData(withdrawAuditPage);
    }

    /**
     * 提现审核通过
     *
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public EditWithdrawYesRes editWithdrawYes(EditWithdrawYesReq req) {
        EditWithdrawYesRes res = new EditWithdrawYesRes();
//        Withdraw withdraw = withdrawMapper.selectById(req.getWithdrawId());
//        //判断是否是链上的
//        if (!withdraw.getTransferMode().equals(1)) {
//            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_ADMIN_APP_001);
//        }
//        if (ObjectUtil.isNotNull(withdraw)) {
//            if (!withdraw.getStatus().equals(TokenApprovedStateEnum.PENDING.getValue())) {
//                throw new ApiServiceException(LetokenApiResponseEnum.ERROR_ADMIN_APP_004);
//            }
//            withdraw.setApprovedDate(LocalDateTime.now());
//            AdminUserInfoRes adminUserInfoRes = AppLoginTokenRedis.me().getAdminUserInfoRes();
//            withdraw.setApprovedBy(adminUserInfoRes.getName());
//            withdraw.setApprovedState(TokenApprovedStateEnum.ADOPT.getValue());
//            withdrawMapper.updateById(withdraw);
//            WithdrawReq withdrawReq = new WithdrawReq();
//            withdrawReq.setId(withdraw.getId().toString());
//            walletMQManager.withdraw(rabbitTemplate, withdrawReq, 1000);
//            res.setWithdrawId(req.getWithdrawId());
//        }
        return res;
    }

    /**
     * 提现审核拒绝
     *
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public EditWithdrawNoRes editWithdrawNo(EditWithdrawNoReq req) {
        EditWithdrawNoRes res = new EditWithdrawNoRes();
        Withdraw withdraw = withdrawMapper.selectById(req.getWithdrawId());
        //判断是否是链上的
        if (!withdraw.getTransferMode().equals(1)) {
            throw new ApiServiceException(LetokenApiResponseEnum.ERROR_ADMIN_APP_001);
        }
        if (ObjectUtil.isNotNull(withdraw)) {
            if (!withdraw.getStatus().equals(TokenApprovedStateEnum.PENDING.getValue())) {
                throw new ApiServiceException(LetokenApiResponseEnum.ERROR_ADMIN_APP_004);
            }
            withdraw.setStatus(TokenTransactionStatusEnum.FAIL.getValue());
            withdraw.setApprovedState(TokenApprovedStateEnum.REFUSE.getValue());
            withdraw.setApprovedDate(LocalDateTime.now());
            AdminUserInfoRes adminUserInfoRes = AppLoginTokenRedis.me().getAdminUserInfoRes();
            withdraw.setApprovedBy(adminUserInfoRes.getName());
            withdrawMapper.updateById(withdraw);
            BigDecimal amount = withdraw.getAmount();
            AppUserWallet appUserWallet = appUserWalletManager.queryWalletByToken(withdraw.getUserId(), withdraw.getTokenId());
            // 如果提现金额大于冻结金额 就要审批失败
            if (amount.compareTo(appUserWallet.getFreezeBalance()) > 0) {
                throw new ApiServiceException(LetokenApiResponseEnum.ERROR_ADMIN_APP_002);
            }
            //修改用户资产记录
            AppUserAssetsHistory appUserAssetsHistory = historyManager.queryBySn(withdraw.getUserId(), withdraw.getSn());
            if (appUserAssetsHistory != null) {
                appUserAssetsHistory.setStatus(TokenTransactionStatusEnum.FAIL.getValue());
                appUserAssetsHistory.setUpdateTime(LocalDateTime.now());
                appUserAssetsHistory.updateById();
            }
            //解冻金额
            int updateWallet = appUserWalletService.updateUserAmountByUserIDandCoin(amount,
                    amount.negate(), BigDecimal.ZERO, withdraw.getUserId(), withdraw.getTokenId());
            if (updateWallet == 0) {
                log.error("提现审核拒绝失败！提现id：{} 用户id： {}", withdraw.getId(), withdraw.getUserId());
                throw new ApiServiceException(LetokenApiResponseEnum.ERROR_ADMIN_APP_002);
            }

            res.setWithdrawId(req.getWithdrawId());
        }
        return res;
    }

    @Override
    public PageData<QueryQuickswapListRes> queryQuickswapList(QueryQuickswapListReq req) {
        Page<QueryQuickswapListRes> page = new Page<>(req.getPageReq().getPage(), req.getPageReq().getSize());
        Page<QueryQuickswapListRes> QuickswapPage = appUserSwapRecordMapper.queryQuickswapList(page, req);
        return PageDataUtil.getPageData(QuickswapPage);
    }

    @Override
    public PageData<QueryAppAssetsListRes> queryUserAssetsList(QueryAppAssetsListReq req) {
        Page<QueryAppAssetsListRes> page = new Page<>(req.getPageReq().getPage(), req.getPageReq().getSize());
        Page<QueryAppAssetsListRes> QuickswapPage = appUserWalletMapper.queryUserAssetsList(page, req);
        return PageDataUtil.getPageData(QuickswapPage);
    }

    @Override
    public QueryWithdrawHistoryRes queryWithdrawHistory(Integer userId) {
        QueryWithdrawHistoryRes res = appUserIssueMapper.queryIssueByUserId(userId);
        if (res == null) {
            res = new QueryWithdrawHistoryRes();
        }
        QueryWithdrawHistoryRes rechargeRes = appUserRechargeMapper.queryRechargeByUserId(userId);
        if (rechargeRes != null) {
            res.setRechargeNum(rechargeRes.getRechargeNum());
        }
        List<AppUserWallet> appUserWalletList = appUserWalletManager.queryWalletByUserId(userId, Arrays.asList(LetokenTokenTypeEnum.LET.getId(), LetokenTokenTypeEnum.USDT.getId()));
        for (AppUserWallet appUserWallet : appUserWalletList) {
            if (appUserWallet.getTokenId().equals(LetokenTokenTypeEnum.LET.getId())) {
                res.setLetNum(appUserWallet.getAvailableBalance());
            } else {
                res.setUsdtNum(appUserWallet.getAvailableBalance());
            }
        }
        return res;
    }


    @Override
    public PageData<?> queryUserAssetsDetailsList(Integer userId, String currency, Integer pageNum, Integer size) {
        Page<AppUserAssetsHistory> page = new Page<>(pageNum, size);

        userAssetsHistoryMapper.pageList(page, userId, LetokenTokenTypeEnum.nameIdMap.get(currency));
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return new PageData<>(new PageRes(), Collections.EMPTY_LIST);
        }


        HashSet<String> snList = null;
        List<String> waitCheckSnList = new ArrayList<>();
        for (AppUserAssetsHistory record : page.getRecords()) {
            if (StringUtils.isNotEmpty(record.getSn())) {
                if (record.getSn().startsWith("WI")) {
                    String sn = record.getSn().replaceFirst("I", "D");
                    waitCheckSnList.add(sn);
                    record.setSn(sn);
                } else {
                    waitCheckSnList.add(record.getSn());
                }
            }
        }
        if (!CollectionUtils.isEmpty(waitCheckSnList)) {
            snList = withdrawMapper.existSNList(userId, waitCheckSnList);
        }

        List<QueryAssetsHistoryRes> list = new ArrayList<>(page.getRecords().size());
        for (AppUserAssetsHistory record : page.getRecords()) {
            QueryAssetsHistoryRes res = new QueryAssetsHistoryRes();
            res.setTokenCurrency(LetokenTokenTypeEnum.idNameMap.get(record.getTokenId()));
            String typeDesc = AppTokenTransactionsTypeDescEnum.typeDescMap.get(record.getType());

            if (!CollectionUtils.isEmpty(snList) && StringUtils.isNotEmpty(record.getSn()) && snList.contains(record.getSn())) {
                if (Objects.equals(record.getType(), AppTokenTransactionsTypeDescEnum.RECHARGE.type)) {
                    typeDesc = "站内转入";
                } else if (Objects.equals(record.getType(), AppTokenTransactionsTypeDescEnum.WITHDRAW.type)) {
                    typeDesc = "站内转出";
                }
            }

            res.setTypeDesc(typeDesc);
            res.setQuantityChange(record.getAmount());
            res.setModifiedBalance(record.getBalance());
            res.setCreateTime(record.getCreateTime());
            list.add(res);
        }
        return new PageData<>(new PageRes(pageNum, list.size(), page.getTotal()), list);
    }

    @Override
    public List<QueryAppUserTokenAilableBalanceRes> queryUserAvailableBalance(Integer userId) {
        return withdrawMapper.queryUserAvailableBalance(userId);
    }

    @Override
    public List<QueryTeamAchievementRes> queryTeamAchievementList(QueryTeamAchievementReq req) {

        String[] userIds = StringUtils.split(req.getUserId(), ",");
        List<QueryTeamAchievementRes> resList = new ArrayList<>();
        for (String userId : userIds) {
            Integer userIdInt = Integer.valueOf(userId);
            //判断用户是否存在
            boolean flag = userManager.queryUserExistById(userIdInt);
            if (!flag) {
                QueryTeamAchievementRes res = new QueryTeamAchievementRes();
                res.setUserId(userIdInt);
                res.setRemarks(1);
                resList.add(res);
                continue;
            }
            QueryTeamAchievementReq reqTwo = new QueryTeamAchievementReq();
            reqTwo.setUserId(userId);
            reqTwo.setStartTime(req.getStartTime());
            reqTwo.setSendTime(req.getSendTime());
            // 团队业绩和已流通
            QueryTeamAchievementRes res = appUserTeamMapper.circulationAndAmount(reqTwo);
            if (res == null) {
                res = new QueryTeamAchievementRes();
                res.setTeamAchievement(BigDecimal.ZERO);
                res.setCirculation(BigDecimal.ZERO);
            }
            res.setRemarks(0);
            res.setUserId(userIdInt);
            if (res.getTeamAchievement() == null) {
                res.setTeamAchievement(BigDecimal.ZERO);
            }
            if (res.getCirculation() == null) {
                res.setTeamAchievement(BigDecimal.ZERO);
            }
            //平台互转(LET)
            BigDecimal platformTransferLet = appUserTeamMapper.queryPlatformTransferLet(reqTwo);
            res.setPlatformTransferLet(platformTransferLet == null ? BigDecimal.ZERO : platformTransferLet);
            // 充值和  u闪兑let
            RechargeAndSwapDto dto = appUserTeamMapper.queryRechargeAndSwap(reqTwo);
            if (dto == null) {
                res.setRechargeToLet(BigDecimal.ZERO);
            } else {
                if (dto.getRechargeAmount() == null) {
                    dto.setRechargeAmount(BigDecimal.ZERO);
                }
                if (dto.getSwapAmount() == null) {
                    dto.setSwapAmount(BigDecimal.ZERO);
                }
                res.setRechargeToLet(dto.getSwapAmount());
//                res.setRechargeToLet(
//                        dto.getRechargeAmount().compareTo(dto.getSwapAmount()) < 0 ? dto.getRechargeAmount() : dto.getSwapAmount()
//                );
            }


            // let闪兑usdt
            BigDecimal letSwapUsdt = appUserTeamMapper.queryLetSwapUsdt(reqTwo);
            res.setLetSwapUsdt(letSwapUsdt == null ? BigDecimal.ZERO : letSwapUsdt);
            // 提现usdt
            BigDecimal withdrawUsdt = appUserTeamMapper.queryWithdrawUsdt(reqTwo);
            res.setWithdrawUsdt(withdrawUsdt == null ? BigDecimal.ZERO : withdrawUsdt);
            resList.add(res);
        }
        return resList;
    }

    @Override
    public QueryUserCountByDateRes queryUserCountByDate() {
        return userMapper.selectCountByDate();
    }

    @Override
    public QueryAppRechargeCountRes queryRechargeCount() {
        QueryAppRechargeCountRes res = appUserRechargeMapper.queryRechargeCount();

        if (null == res) {
            return new QueryAppRechargeCountRes(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO);
        }
        res.setTodayRechargeCount(BigDecimalUtil.twoScaleDown(res.getTodayRechargeCount()));
        res.setYesterdayRechargeCount(BigDecimalUtil.twoScaleDown(res.getYesterdayRechargeCount()));
        res.setThisMonthRechargeCount(BigDecimalUtil.twoScaleDown(res.getThisMonthRechargeCount()));
        res.setRechargeCount(BigDecimalUtil.twoScaleDown(res.getRechargeCount()));

        return res;
    }

    @Override
    public QueryWithdrawCountRes queryWithdrawCount() {
        QueryWithdrawCountRes res = withdrawMapper.queryWithdrawCount();
        if (null == res) {
            return new QueryWithdrawCountRes(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO);
        }
        res.setTodayWithdrawCount(BigDecimalUtil.twoScaleDown(res.getTodayWithdrawCount()));
        res.setYesterdayWithdrawCount(BigDecimalUtil.twoScaleDown(res.getYesterdayWithdrawCount()));
        res.setThisMonthWithdrawCount(BigDecimalUtil.twoScaleDown(res.getThisMonthWithdrawCount()));
        res.setWithdrawCount(BigDecimalUtil.twoScaleDown(res.getWithdrawCount()));
        return res;
    }

    @Override
    public EditWithdrawYesRes auditAgainYes(EditWithdrawYesReq req) {
        EditWithdrawYesRes res = new EditWithdrawYesRes();
//        Withdraw withdraw = withdrawMapper.selectById(req.getWithdrawId());
//        if (withdraw.getStatus().equals(TokenTransactionStatusEnum.COMPLETED.getValue())) {
//            throw new ApiServiceException("该提现记录已通过，请勿重新提现！");
//        }
//        if (withdraw.getTransferMode().equals(0)) {
//            throw new ApiServiceException("此记录为平台内转账，请勿重新转账！");
//        }
//        withdraw.setApprovedDate(LocalDateTime.now());
//
//        if(UserWalletRedisBloomFilter.me().getWithdrawOrder(withdraw.getSn())) {
//            if (Duration.between(withdraw.getCreateTime(), LocalDateTime.now()).toMinutes() < 5) {
//                throw new ApiServiceException("任务正在运行，请稍后"); // 5分钟内防止重复执行
//            }
//        }
//
//        // 清除备注，让异常情况可以重新发起
//        if(!StringUtils.isEmpty(withdraw.getRemark())){
//            withdraw.setRemark("");
//            withdraw.updateById();
//        }
//
//        WithdrawReq withdrawReq = new WithdrawReq();
//        withdrawReq.setId(withdraw.getId().toString());
//        walletMQManager.withdraw(rabbitTemplate, withdrawReq, 1000);
//        res.setWithdrawId(req.getWithdrawId());
        return res;
    }

    @Override
    public List<QueryLineChartRes> queryDepositLineChart(QueryLineChartReq req) {
        List<LocalDate> lineChartTime = DateTimeUtil.getLineChartTime(req);
        List<QueryLineChartRes> lineChartRes = appUserRechargeMapper.queryDepositLineChart(req);
        return LineChartUtil.getLineChartRes(lineChartTime, lineChartRes);
    }

    @Override
    public List<QueryLineChartRes> queryUserLineChart(QueryLineChartReq req) {
        List<LocalDate> lineChartTime = DateTimeUtil.getLineChartTime(req);
        List<QueryLineChartRes> lineChartRes = userMapper.queryUserLineChart(req);
        return LineChartUtil.getLineChartRes(lineChartTime, lineChartRes);
    }

    @Override
    public List<QueryLineChartRes> queryWithdrawLineChart(QueryLineChartReq req) {
        List<LocalDate> lineChartTime = DateTimeUtil.getLineChartTime(req);
        List<QueryLineChartRes> lineChartRes = withdrawMapper.queryWithdrawLineChart(req);
        return LineChartUtil.getLineChartRes(lineChartTime, lineChartRes);
    }

    @Override
    public void isLockedUser(IsLockedUserReq req) {
        Integer userId = req.getUserId();
        Boolean locked = req.getLocked();
        Integer adminUserId = WebUtils.getAdminUserId();
        int flag = appUserLockedManager.setUserLocked(userId, locked, adminUserId);
        if (flag < 1) {
            throw new ApiServiceException("修改失败！");
        }
    }

    @Override
    public List<QueryAppAssetsSumRes> queryUserAssetsSum() {
        return withdrawMapper.queryUserAssetsSum();
    }


    Map<Integer, String> appEcoTypeDescMap = new HashMap<>() {{
        put(3, "小区铸币发行");
        put(12, "小区商城消费 ");
        put(19, "小区商城消费 ");

    }};


    @Override
    public PageData<?> queryUserEcoHistoryList(Integer userId, Integer pageNum, Integer size) {
        Page<AppEcoHistory> page = new Page<>(pageNum, size);
        LambdaQueryWrapper<AppEcoHistory> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(AppEcoHistory::getUserId, userId);
        lambdaQueryWrapper.orderByDesc(AppEcoHistory::getCreateTime);

        appEcoHistoryMapper.selectPage(page, lambdaQueryWrapper);
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return new PageData<>(new PageRes(), Collections.EMPTY_LIST);
        }
        List<QueryAppEcoHistoryRes> list = new ArrayList<>(page.getRecords().size());
        for (AppEcoHistory record : page.getRecords()) {
            QueryAppEcoHistoryRes res = new QueryAppEcoHistoryRes();
            res.setUserId(record.getUserId());
            res.setAmbLevelName(record.getAmbLevel().toString());
            res.setTypeDesc(appEcoTypeDescMap.get(record.getType()));
            res.setAmount(record.getAmount());
            res.setBalance(record.getBalance());
            res.setSource(record.getSource());
            res.setCreateTime(record.getCreateTime());
            list.add(res);
        }
        return new PageData<>(new PageRes(pageNum, list.size(), page.getTotal()), list);
    }


    @Override
    public PageData<UpLevelHistoryRes> ecoLevelHistory(EcoLevelHistoryReq req) {
        Page<UpLevelHistoryRes> page = new Page<>(req.getPageReq().getPage(), req.getPageReq().getSize());
        Page<UpLevelHistoryRes> QuickswapPage = levelUpHistoryMapper.ecoLevelHistory(page, req);
        return PageDataUtil.getPageData(QuickswapPage);
    }


}
